package com.hepinghospital.user.ui.activity.nursing.fragment

import android.os.Bundle
import android.text.TextUtils
import android.view.View
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.chad.library.adapter.base.BaseQuickAdapter
import com.hepinghospital.user.R
import com.hepinghospital.user.adapter.NursingOrderAdapter
import com.hepinghospital.user.base.BaseApplication
import com.hepinghospital.user.base.BaseFragment
import com.hepinghospital.user.ui.activity.nursing.NursingOrderDetailActivity
import com.hepinghospital.user.ui.dialog.ChooseDialog
import com.hepinghospital.user.ui.dialog.NursingEvaluateDialog
import com.hepinghospital.user.util.ToastUtil
import com.rest.business.RestProxy
import com.rest.observer.BaseObserver
import com.rest.response.NursingOrderResponse
import com.rest.response.NursingOrderResponse.NursingOrder
import com.rest.response.WxPayBean
import com.scwang.smartrefresh.layout.SmartRefreshLayout
import com.scwang.smartrefresh.layout.api.RefreshLayout
import com.tencent.mm.opensdk.modelpay.PayReq
import com.tencent.mm.opensdk.openapi.IWXAPI
import com.tencent.mm.opensdk.openapi.WXAPIFactory
import java.lang.Exception

/**
 * @Description
 * @Author WuJianFeng
 * @Date 2022/8/9 17:19
 */
class HomeNurseFragment : BaseFragment() {


    var recyclerView: RecyclerView? = null

    var refreshLayout: SmartRefreshLayout? = null
    var clEmpty: ConstraintLayout? = null


    var page = 1

    var mAdapter: NursingOrderAdapter? = null
    var data = ArrayList<NursingOrder>()

    private var mChooseDialog: ChooseDialog? = null
    private var mEvaluateDialog: NursingEvaluateDialog? = null

    var wxApi: IWXAPI? = null

    override fun getLayoutResource(): Int {
        return R.layout.fragment_nursing_my_order
    }

    override fun initView() {

    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        recyclerView = rootView.findViewById<RecyclerView>(R.id.recyclerView)
        refreshLayout = rootView.findViewById<SmartRefreshLayout>(R.id.refreshLayout)
        clEmpty = rootView.findViewById<ConstraintLayout>(R.id.cl_empty)
        val manager = LinearLayoutManager(context)
        manager.orientation = LinearLayoutManager.VERTICAL
        recyclerView?.layoutManager = manager
        mAdapter = NursingOrderAdapter(data)
        recyclerView?.adapter = mAdapter
        refreshLayout?.isEnableLoadMore = false
        refreshLayout?.setOnRefreshListener { refreshLayout: RefreshLayout? ->
            page = 1
            getOrders()
        }
        refreshLayout?.setOnLoadMoreListener { refreshLayout: RefreshLayout? ->
            page++
            getOrders()
        }
        mAdapter?.addChildClickViewIds(R.id.tv_cancel, R.id.tv_pay, R.id.tv_evaluate)
        mAdapter?.setOnItemChildClickListener { adapter: BaseQuickAdapter<*, *>?, view: View, position: Int ->
            when (view.id) {
                R.id.tv_cancel -> showChooseDialog(data[position].orderId)
                R.id.tv_pay -> nurseRequestPay(
                    data[position].orderId,
                    data[position].orderAmount
                )
                R.id.tv_evaluate -> showEvaluateDialog(data[position].appointmentId)
            }
        }
        mAdapter?.setOnItemClickListener { adapter: BaseQuickAdapter<*, *>?, view: View?, position: Int ->
            val bundle = Bundle()
            bundle.putString("appointmentId", data[position].appointmentId)
            startActivity(NursingOrderDetailActivity::class.java, bundle)
        }
    }


    /**
     * 获取护理预约订单
     */
    private fun getOrders() {
        RestProxy.getInstance().getNursingOrders(page, object : BaseObserver<NursingOrderResponse>() {
                override fun onSuccess(result: NursingOrderResponse) {
                    if (result.list == null || result.list.size == 0){
                        clEmpty?.visibility = View.VISIBLE
                        refreshLayout?.visibility = View.GONE
                    }else{
                        clEmpty?.visibility = View.GONE
                        refreshLayout?.visibility = View.VISIBLE

                        if (page == 1) {
                            data.clear()
                            data.addAll(result.list)
                            refreshLayout?.finishRefresh()
                        } else {
                            data.addAll(result.list)
                            refreshLayout?.finishLoadMore()
                        }

                        mAdapter?.notifyDataSetChanged()

                        if (result.isEnd) {
                            refreshLayout?.finishLoadMoreWithNoMoreData()
                        }

                    }



                }

                override fun onError(e: Throwable) {
                    super.onError(e)
                    ToastUtil.showToast(mContext,e.message)
                    if (page == 1) {
                        refreshLayout?.finishRefresh(false)
                    } else {
                        refreshLayout?.finishLoadMore(false)
                    }
                }
            })
    }

    //取消订单
    private fun cancleAppointment(orderId: String?= "") {
        if (TextUtils.isEmpty(orderId)) return
        RestProxy.getInstance().appointmentCancle(orderId, object : BaseObserver<String?>() {
            override fun onSuccess(result: String?) {
                getOrders()
            }
        })
    }

    private fun nurseRequestPay(orderId: String?= "", orderAmount: String?= "") {
        if (TextUtils.isEmpty(orderId) || TextUtils.isEmpty(orderAmount)) return
        BaseApplication.currentOrderId = orderId
        BaseApplication.diagnoseType = -1
        BaseApplication.isNursingPay = true
        BaseApplication.isNursiningList = true
        RestProxy.getInstance()
            .nurseRequestPay(orderId, orderAmount, object : BaseObserver<WxPayBean>() {
                override fun onSuccess(wxPayBean: WxPayBean) {
//                BaseApplication.currentWXId = wxPayBean.getAppid();
                    wxApi = WXAPIFactory.createWXAPI(mContext, wxPayBean.appid)
                    //                // 将该app注册到微信
                    wxApi?.registerApp(wxPayBean.appid)
                    val request = PayReq()
                    request.appId = wxPayBean.appid
                    request.partnerId = wxPayBean.partnerid
                    request.prepayId = wxPayBean.prepayid
                    request.packageValue = "Sign=WXPay"
                    request.nonceStr = wxPayBean.noncestr
                    request.timeStamp = wxPayBean.timestamp
                    //                request.signType = wxPayBean.getGetType();
                    request.sign = wxPayBean.sign
                    wxApi?.sendReq(request)
                }

                override fun onError(e: Throwable) {
                    ToastUtil.onError(mContext, e)
                }
            })
    }

    /**
     * 取消订单 弹框
     */
    private fun showChooseDialog(orderId: String? = "") {
        if (TextUtils.isEmpty(orderId)) return
        mChooseDialog = ChooseDialog.newInstance()
        mChooseDialog?.show(childFragmentManager, "mDialog")
        mChooseDialog?.setText("是否取消订单", "确定", "取消")
        mChooseDialog?.setmListener(object : ChooseDialog.OnItemClickListener {
            override fun onConfirm() {
                cancleAppointment(orderId)
            }

            override fun onCancel() {}
        })
    }

    /**
     * 评价弹框
     */
    private fun showEvaluateDialog(appointmentId: String) {
        mEvaluateDialog = NursingEvaluateDialog.newInstance(appointmentId)
        mEvaluateDialog?.show(childFragmentManager, "EvaluateDialog")
        mEvaluateDialog?.setmListener(object : NursingEvaluateDialog.OnItemClickListener {
            override fun onConfirm() {
                getOrders()
            }

            override fun onCancel() {}
        })
    }

    override fun initData() {
    }

    override fun onResume() {
        super.onResume()
        getOrders()
    }
}